﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Datory;
using Microsoft.AspNetCore.Mvc;
using XBLMS.Core.Utils;
using XBLMS.Enums;
using XBLMS.Models;
using XBLMS.Utils;

namespace XBLMS.Web.Controllers.Admin.Settings.Users
{
    public partial class UsersGroupController
    {
        [HttpGet, Route(Route)]
        public async Task<ActionResult<GetResult>> Get([FromQuery] GetRequest request)
        {
            if (!await _authManager.HasPermissionsAsync())
            {
                return this.NoAuth();
            }

            var resultGroups = new List<UserGroup>();
            var allGroups = await _userGroupRepository.GetListAsync();
            if(allGroups!=null && allGroups.Count > 0)
            {
                foreach(var group in allGroups)
                {
                    var creator = await _administratorRepository.GetByUserIdAsync(group.CreatorId);
                    group.Set("TypeName", group.GroupType.GetDisplayName());
                    if (creator != null)
                    {
                        group.Set("CreatorId", creator.Id);
                        group.Set("CreatorDisplayName", creator.DisplayName);
                    }

                    if (!string.IsNullOrEmpty(request.Search))
                    {
                        if (group.GroupName.Contains(request.Search) || group.Description.Contains(request.Search))
                        {
                            resultGroups.Add(group);
                        }
                    }
                    else
                    {
                        resultGroups.Add(group);
                    }
           

                }
            }
            return new GetResult
            {
                Groups = resultGroups
            };
        }
    }
}
